import React from 'react';
import {
  Box,
  Container,
  Paper,
  Typography,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  LinearProgress,
  IconButton,
  Chip,
  Tooltip,
} from '@mui/material';
import { motion } from 'framer-motion';
import DeleteIcon from '@mui/icons-material/Delete';
import PauseIcon from '@mui/icons-material/Pause';
import PlayArrowIcon from '@mui/icons-material/PlayArrow';
import { useDownload, DownloadItem } from '../DownloadContext';

const DownloadHistory: React.FC = () => {
  const { downloads, pauseDownload, resumeDownload, removeDownload } = useDownload();



  const formatSize = (bytes: number): string => {
    const sizes = ['B', 'KB', 'MB', 'GB'];
    let i = 0;
    let size = bytes;
    while (size >= 1024 && i < sizes.length - 1) {
      size /= 1024;
      i++;
    }
    return `${size.toFixed(2)} ${sizes[i]}`;
  };

  const formatTime = (seconds: number): string => {
    if (seconds === 0) return '-';
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}分${remainingSeconds}秒`;
  };

  const formatSpeed = (bytesPerSecond: number): string => {
    if (bytesPerSecond === 0) return '-';
    return `${formatSize(bytesPerSecond)}/s`;
  };

  const getStatusColor = (status: DownloadItem['status']): 'primary' | 'secondary' | 'error' | 'info' | 'success' | 'warning' => {
    switch (status) {
      case 'downloading':
        return 'primary';
      case 'completed':
        return 'success';
      case 'error':
        return 'error';
      case 'paused':
        return 'warning';
      default:
        return 'primary';
    };
  };

  const getStatusText = (status: DownloadItem['status']): string => {
    switch (status) {
      case 'downloading':
        return '下载中';
      case 'completed':
        return '已完成';
      case 'error':
        return '错误';
      case 'paused':
        return '已暂停';
      default:
        return '未知';
    }
  };

  return (
    <Container maxWidth="lg">
      <Box
        component={motion.div}
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
        sx={{ mt: 4 }}
      >
        <Paper elevation={3} sx={{ p: 3 }}>
          <Typography variant="h5" gutterBottom>
            我的下载
          </Typography>
          <TableContainer>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>文件名</TableCell>
                  <TableCell align="right">大小</TableCell>
                  <TableCell align="center">状态</TableCell>
                  <TableCell align="center">进度</TableCell>
                  <TableCell align="right">速度</TableCell>
                  <TableCell align="right">剩余时间</TableCell>
                  <TableCell align="center">操作</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {downloads.map((download) => (
                  <TableRow key={download.id}>
                    <TableCell component="th" scope="row">
                      {download.title}
                    </TableCell>
                    <TableCell align="right">{formatSize(download.size)}</TableCell>
                    <TableCell align="center">
                      <Chip
                        label={getStatusText(download.status)}
                        color={getStatusColor(download.status)}
                        size="small"
                      />
                    </TableCell>
                    <TableCell>
                      <Box sx={{ width: '100%', mr: 1 }}>
                        <LinearProgress
                          variant="determinate"
                          value={download.progress}
                          color={getStatusColor(download.status)}
                        />
                        <Typography variant="body2" color="text.secondary" align="center">
                          {`${Math.round(download.progress)}%`}
                        </Typography>
                      </Box>
                    </TableCell>
                    <TableCell align="right">{formatSpeed(download.speed)}</TableCell>
                    <TableCell align="right">
                      {formatTime(download.timeRemaining)}
                    </TableCell>
                    <TableCell align="center">
                      <Box>
                        {download.status === 'downloading' ? (
                          <Tooltip title="暂停">
                            <IconButton size="small" onClick={() => pauseDownload(download.id)}>
                              <PauseIcon />
                            </IconButton>
                          </Tooltip>
                        ) : download.status === 'paused' ? (
                          <Tooltip title="继续">
                            <IconButton size="small" onClick={() => resumeDownload(download.id)}>
                              <PlayArrowIcon />
                            </IconButton>
                          </Tooltip>
                        ) : null}
                        <Tooltip title="删除">
                          <IconButton size="small" color="error" onClick={() => removeDownload(download.id)}>
                            <DeleteIcon />
                          </IconButton>
                        </Tooltip>
                      </Box>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </Paper>
      </Box>
    </Container>
  );
};

export default DownloadHistory;